﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace QJY.Common
{
    public class JwtHelper
    {

        static readonly string baseData = "abcdefghijklmnopqrstuvwxyz0123456789-";
        static readonly string basekey = "851215";


        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static TokenJWT CreateJWT(string strUserName)
        {
            TokenJWT Token = new TokenJWT();
            Token.UserName = strUserName;
            string exp = DateTime.Now.AddSeconds(int.Parse(CommonHelp.GetConfig("exptime", "24200"))).ToUniversalTime().Ticks.ToString();
            Token.Exp = exp;
            Token.Token = "";
            string strTemp = strUserName + "-" + exp;
            string strToken = "";
            for (int counter = 0; counter < strTemp.Length; counter++)
            {
                string Temp = baseData.IndexOf(strTemp[counter].ToString().ToLower()).ToString().PadLeft(2, '0');
                strToken = strToken + Temp;
            }
            Token.Token = strToken;
            return Token;
        }

        public static TokenJWT DePJWT(string strCode)
        {


            TokenJWT Token = new TokenJWT();
            List<int> listIndex = new List<int>();
            for (int i = 0; i < strCode.Length; i += 2)
            {
                if ((strCode.Length - i) > 2)//如果是，就截取
                {
                    listIndex.Add(int.Parse(strCode.Substring(i, 2)));
                }
                else
                {
                    listIndex.Add(int.Parse(strCode.Substring(i)));//如果不是，就截取最后剩下的那部分
                }
            }
            string strTemp = "";
            foreach (var index in listIndex)
            {
                strTemp = strTemp + baseData[index];
            }
            Token.UserName = strTemp.Split('-')[0];
            Token.Exp = strTemp.Split('-')[1];
            Token.Token = strCode;

            return Token;

        }

    }

    /// <summary>
    /// 令牌
    /// </summary>
    public class TokenJWT
    {
        /// <summary>
        /// Id
        /// </summary>
        public string Token { get; set; }
        public string UserName { get; set; }
        public string Exp { get; set; }
    }
}